import { saveTimeLine } from "@/api/content/timeLine";
import { LOVE_TIME_LINE_TYPE } from "@/constants/configKey.constant";
import { TimeLine } from "@/types/content/timeLine";
import { DatePicker, Form, Input, message, Modal, Spin } from "antd";
import { useForm } from "antd/es/form/Form";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
interface Props {
  isModalOpen: boolean;
  optionType: "add" | "edit";
  oldInfo?: TimeLine.Row;
  close?: () => void;
  change?: () => void;
}
export default function TimeLineOption(props: Props) {
  const [loading, setLoading] = useState(false);
  const [form] = useForm();
  const [messageApi] = message.useMessage();
  /**
   * 添加接口
   * @param data
   */
  const saveTimeLineInf = async (data: TimeLine.Form) => {
    setLoading(true);
    const res = await saveTimeLine(data);
    setLoading(false);
    if (res.code === 200) {
      messageApi.success("保存成功");
      props.close && props.close();
      props.change && props.change();
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { time, content } = values;
      const params = {
        time:dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
        content,
        type: LOVE_TIME_LINE_TYPE,
      };
      if (props.optionType === "add") {
        saveTimeLineInf(params);
      } else if (props.optionType === "edit") {
        saveTimeLineInf({
          ...(props.oldInfo || {}),
          ...params,
          id: props.oldInfo?.id,
        });
      }
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  useEffect(() => {
    if (props.optionType === "edit") {
      form.setFieldsValue({
        ...props.oldInfo || {},
        time:dayjs(props.oldInfo?.time)
      });
    }
  }, [form, props.oldInfo, props.optionType]);
  return (
    <Modal
      title={props.optionType === "add" ? "新增时间轴" : "修改时间轴"}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          name="tagOptionForm"
          size="middle"
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item<TimeLine.Form>
            name="time"
            label="时间"
            rules={[{ required: true, message: "时间不能为空" }]}
          >
             <DatePicker format="YYYY-MM-DD HH:mm:ss" showTime />
          </Form.Item>

          <Form.Item<TimeLine.Form>
            name="content"
            label="内容"
            rules={[{ required: true, message: "内容不能为空" }]}
          >
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}
